package com.xisoft.handle;

import com.xisoft.base.BaseModel;
import com.xisoft.base.ConfigTemplate;
import com.xisoft.common.ProcessorException;
import com.xisoft.utils.StringUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.zip.ZipOutputStream;

/**
 * @author xzh
 * @Date 2021/8/16 17:44
 * @description 模板处理器
 * 注意：本内容仅限于上海熙软科技有限公司内部，传阅，禁止外泄以及用于其他商业目的
 */
public class TempldateHandler implements Handler {

    Logger log = LoggerFactory.getLogger(TempldateHandler.class);
    private Configuration cfg;

    public TempldateHandler() {

        super();
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void init() throws Exception {

        cfg = new Configuration();
        // 模版文件所在的目录
        String classPath = getClass().getResource("/").getPath();
        cfg.setDirectoryForTemplateLoading(new File(classPath + File.separator + "template"));
    }

    /**
     * 建立模版
     * 用参数来区分是哪个 ftl 文件--hou
     *
     * @param @throws Exception
     * @return void
     * @throws
     * @description
     * @title buildTemplate
     */
    @Override
    public void handle(BaseModel model, HandlerChain chain) throws ProcessorException {

        perfectModel(model);
        File path = new File(model.dbConfig.BASE_PATH);

        if (!path.exists()) {
            path.mkdirs();
        }
        ConfigTemplate
                .getTemplates(model)
                .stream()
                .forEach(item ->
                {
                    create(model, item, path);
                });

        chain.handle(model);
    }

    private void create(BaseModel model, ConfigTemplate item, File path) {
        BufferedWriter out = null;
        File tempFile = null;
        Template template = null;
        ZipOutputStream zos = null;
        try {
            template = cfg.getTemplate(item.tempdatename);
            tempFile = new File(path, item.generateDir);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            log.info("filename = " + item.filename);
            tempFile = new File(tempFile, item.filename);
            if (!tempFile.exists()) {
                tempFile.createNewFile();
            }
            out = new BufferedWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(tempFile, false), "UTF-8"));

            if ("Y".equals(model.dbConfig.TABLE2PACKAGENAME)) {
                model.setSubPackageName(model.getvName() + ".");
            } else {
                model.setSubPackageName("");
            }
            template.process(model, out);
            log.info("代码生成 {}/{}", item.generateDir, item.filename);
        } catch (Exception e) {
            log.info(StringUtil.toString(e));
        } finally {
            if (null != out) {
                try {
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    log.info(StringUtil.toString(e));
                }
            }
        }
    }

    /**
     * @param model
     * @description 方法描述：完善Model
     */
    private void perfectModel(BaseModel model) {

        model.setdName(model.getTable().getdName());
        model.setvName(model.getTable().getvName());
        model.setCOMMENTS(model.getTable().getCOMMENTS());
        model.setColumns(model.getTable().getColumns());
        //		model.setUnicode_titlename(UnicodeUtil.chinaToUnicode(model.titlename));
    }

}
